import React, { useState, useEffect } from 'react';

import { Button, List, Skeleton, Avatar, message } from 'antd';

import styles from './index.less';

const timeout = async (time = 3000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ msg: '请求超时' });
    }, time);
  });
};

export default function IndexPage() {
  const [initLoading, setInitLoading] = useState(true);
  const [loading, setLoading] = useState(false);

  const [searchParams, setSearchParams] = useState({
    keywords: '海阔天空',
    limit: 3,
    offset: 1,
  });

  const [list, setList] = useState([]);

  const getData = async (obj) => {
    const { keywords = '海阔天空', limit = 3, offset } = obj;
    setLoading(true);

    const data = []
      .concat([...new Array(limit)])
      .map(() => ({ loading: true, name: {} }));

    setList((prev) => prev.concat(data));

    try {
      const res = await Promise.race([
        timeout(),
        fetch(
          `/netease-music/search?keywords=${keywords}&limit=${limit}&offset=${offset}`,
          {},
        ).then((result) => result.json()),
      ]);

      setLoading(false);

      if (res && res.msg) {
        message.error(res.msg);
        return;
      }

      if (res && res.code === 200) {
        setList((prev) => {
          const newData = [...prev];
          newData.pop();
          newData.pop();
          newData.pop();

          return newData.concat(res.result.songs);
        });
        return;
      }
    } catch (error) {
      message.error('未知错误');
      setLoading(false);
      setList([]);
    }
  };

  useEffect(() => {
    setInitLoading(false);
  }, []);

  useEffect(() => {
    getData(searchParams);
    setInitLoading(false);
  }, [searchParams]);

  const onLoadMore = async () => {
    if (list.length < 100) {
      setSearchParams((prev) => ({
        ...prev,
        offset: prev.offset + 1,
      }));
    }
  };

  const loadMore =
    !initLoading && !loading ? (
      <div
        style={{
          textAlign: 'center',
          marginTop: 12,
          height: 32,
          lineHeight: '32px',
        }}
      >
        <Button onClick={onLoadMore}>loading more</Button>
      </div>
    ) : null;

  return (
    <>
      <h1>hello world</h1>
      <List
        className="demo-loadmore-list"
        loading={initLoading}
        itemLayout="horizontal"
        loadMore={loadMore}
        dataSource={list}
        renderItem={(item) => (
          <List.Item>
            <Skeleton avatar title={false} loading={item.loading} active>
              <List.Item.Meta
                avatar={<Avatar src={item.album?.artist?.img1v1Url} />}
                title={<a>{item.album?.name}</a>}
                description="Ant Design, a design language for background applications, is refined by Ant UED Team"
              />
              <div>content</div>
            </Skeleton>
          </List.Item>
        )}
      />
    </>
  );
}
